package com.mengxin.secondkill.service.impl;

import com.mengxin.secondkill.domain.Order;
import com.mengxin.secondkill.mapper.OrderMapper;
import com.mengxin.secondkill.mapper.StockMapper;
import com.mengxin.secondkill.message.req.AddOrderReq;
import com.mengxin.secondkill.message.resp.AddOrderResp;
import com.mengxin.secondkill.msgqueue.StreamMessageListener;
import com.mengxin.secondkill.service.OrderService;
import com.mengxin.secondkill.util.SonwFlakeKeyGenerator;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.stream.Record;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

/**
 * @author mengxin
 * @date 2020/12/24 16:34
 */
@Service
@Slf4j
public class OrderServiceImpl implements OrderService {

    @Autowired
    SonwFlakeKeyGenerator sonwFlakeKeyGenerator;

    @Autowired
    OrderMapper orderMapper;

    @Autowired
    StockMapper stockMapper;

    @Autowired
    StreamMessageListener streamMessageListener;

    @Override
    public AddOrderResp addOrder(AddOrderReq req, String group, Record<String, ?> record) {
        Long orderId = orderMapper.queryIdByNumber(req.getOrderNumber());
        if(orderId!=null){
            //保证幂等性
            log.info("流水号"+req.getOrderNumber()+"已生成订单，避免重复消费已忽略此消息");
            //通知redis消息处理成功
            streamMessageListener.ackMessage(group, record);
            return null;
        }
        Order order = new Order();
        BeanUtils.copyProperties(req,order);
        order.setCreateTime(LocalDateTime.now());
        //数据库生成订单
        orderMapper.insertSelective(order);
        //数据库扣减库存
        stockMapper.updateStockSum(req.getGoodsId(),req.getModelId(),req.getSum());
        //通知redis消息处理成功
        streamMessageListener.ackMessage(group, record);
        AddOrderResp resp = new AddOrderResp(order);
        return resp;
    }
}
